import { useMainStore, useUserStore } from '@/store'
import { clearPending } from '@/axios/tool/cancelRequest'
import {
  menuRoutes,
  menuAuthRoutes,
  backstageRoutes,
  exceptionRoutes,
} from './modules'

export const createRouterGuards = router => {
  const mainStore = useMainStore()
  const userStore = useUserStore()
  const whitePathList = ['/', '/chat/new']
  router.beforeEach(async (to, from, next) => {
    clearPending()
    const token = localStorage.getItem('token') || null
    if (whitePathList.includes(to.path)) return next()
    if (!token) return userStore.logout()
    if (mainStore.isAddedRoute) return next()
    userStore.role || await userStore.getUserInfo()
    // 动态添加路由
    userStore.getUserAuth && menuRoutes.splice(menuRoutes.length, 0, ...menuAuthRoutes)
    backstageRoutes[0].children.push(...menuRoutes)
    const routesArr = [...backstageRoutes, ...exceptionRoutes]
    routesArr.forEach(item => router.addRoute(item))
    mainStore.setIsAddedRoute(true)
    next({ ...to, replace: true })
  })

  router.afterEach((to, from, failure) => {
    document.title = (to?.meta?.title || document.title)
  })
}
